package com.pro01.backend.controller;

import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.service.UserPromotionService;
import com.pro01.backend.utils.JwtUtil;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 管理员查看促销记录接口
 */
@RestController
@RequestMapping("/admin/promotions")
public class AdminPromotionController {

    @Autowired
    private UserPromotionService userPromotionService;

    /**
     * 提取 JWT Claims
     */
//    private Map<String, Object> getClaims(HttpServletRequest request) {
//        String token = request.getHeader("Authorization");
//        return JwtUtil.parseToken(token);
//    }

    /**
     * 判断是否是管理员
     */
//    private boolean isAdmin(HttpServletRequest request) {
//        Map<String, Object> claims = getClaims(request);
//        return claims != null && "ADMIN".equals(claims.get("role"));
//    }

    /**
     * 判断当前用户是否为管理员
     */
    private boolean isAdmin(HttpServletRequest request) {
        try {
            String role = TokenUtil.getRole(request); // ✅ 直接从工具类取角色
            return "ADMIN".equals(role);
        } catch (Exception e) {
            return false; // token 无效或缺失
        }
    }


    /**
     * 查询所有用户领取的促销奖励记录（分页）
     */
    @GetMapping("/all")
    public Result<PageResult<Map<String, Object>>> getAllUserPromotions(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        if (!isAdmin(request)) {
            return Result.error("无权限，只有管理员可用！");
        }

        try {
            PageResult<Map<String, Object>> pageResult = userPromotionService.getAllUserPromotions(pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
}
